package p8selfSort;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

import java.io.IOException;
import java.util.Date;
import java.util.Random;

public class SearchUtils {
    private Directory directory;
    private IndexReader reader;
    private String[] ids = {"1", "2", "3", "4", "5", "6"};

    private String[] emails = {
            "zhangsan@sina.com",
            "lisi@sina.com",
            "wangwu@sina.com",
            "zhaoliu@sina.com",
            "qianqi@sina.com",
            "sunba@sina.com"};

    private String[] contents = {
            "this aa zhangsan home",
            "this BB are lisi home",
            "this cc wangwu home",
            "this dd zhaoliu home",
            "this is qianqi home",
            "this are sunba.com home"};
    private Date[] dates = {new Date(), new Date(), new Date(), new Date(), new Date(), new Date()};
    private String[] names = {"zhangsan", "lisi", "zhangsan", "zhaoliu", "qianqi", "sunba"};

    private int[] ataches = {2, 3, 1, 4, 5, 5};

    public SearchUtils() {
        this.directory = new RAMDirectory();
        index();
        System.out.println("======RAM索引完成====================");
    }

    /**
     * 一般reader 一个项目只有一个，有些项目的writer也只有一个，也就是
     * 写完后不close(),不close的话怎么提交索引呢，，用 writer.commit();
     */
    public void index() {

        IndexWriter indexWriter = null;
        try {
            IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35));
            System.out.println("=====" + directory);
            indexWriter = new IndexWriter(directory, iwc);
            indexWriter.deleteAll();
            Document document = null;
            Random random=new Random();
            for (int i = 0; i < ids.length; i++) {
                //第三个参数表示 是否存入索引中，
                document = new Document();
                document.add(new Field("id", ids[i], Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
                document.add(new Field("email", emails[i], Field.Store.YES, Field.Index.ANALYZED));
                document.add(new Field("content", contents[i], Field.Store.NO, Field.Index.ANALYZED));
                document.add(new Field("name", names[i], Field.Store.YES, Field.Index.ANALYZED_NO_NORMS));
                //对数字进行索引
                document.add(new NumericField("atache",Field.Store.YES,true).setIntValue(ataches[i]));
                //加权操作比如对shangsan 加权,默认是1.0
                if (emails[i].equals("zhangsan@sina.com") || emails[i].equals("sunba@sina.com")) {
                    document.setBoost(2.0f);
                }
                //对数字和日期进行索引，日期其实就是数字，所以都用numberField
                document.add(new NumericField("date", Field.Store.YES, true).setLongValue(dates[i].getTime()));


                //自定义排序
                int myScore =random.nextInt(600);
                System.out.println("name:"+names[i]+",myScore:"+myScore);
                document.add(new NumericField("myScore",Field.Store.YES,true).setIntValue(myScore));
                indexWriter.addDocument(document);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (indexWriter != null) {
                try {
                    indexWriter.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 一般创建indexreader的时候用单列的，但是有一个问题就是 对于新增或删除或修改的
     * 索引 indexReader感知不到，为了解决这种情况，提供了 IndexReader.openIfChanged(olderReader)
     * （上面的方法创建单列的时候使用）
     * 意思就是如果索引变化了的话 就会重新创建reader
     */
    public IndexSearcher getSearch() throws IOException {
        if (reader == null) {
            reader = IndexReader.open(directory);
        } else {
            IndexReader tr = IndexReader.openIfChanged(reader);
            reader = tr;
        }
        return new IndexSearcher(reader);
    }


    /**
     * 自定义评分字段进行查询
     *
     */
    public void searchSelfSort(Query query,int num) throws IOException {
        IndexSearcher search = getSearch();
        TopDocs tds=null;
        tds= search.search(query, num);
        //totalHits 是总记录数，num 是取多少条，
        System.out.println("一共查询到了" + tds.totalHits);
        ScoreDoc[] scoreDocs = tds.scoreDocs;
        for (ScoreDoc sd : scoreDocs) {
            Document document = search.doc(sd.doc);
            System.out.println("序号："+sd.doc+",score:"+sd.score+",myScore:"+document.get("myScore")+",eamil:"+document.get("email")+",name:"
                    +document.get("name")+",atache:"+document.get("atache"));
        }
        search.close();
    }


}
